<template>
  <div>
    <el-card>
      <div class="title">
        <div class="btn">
          <el-button type="primary" @click="showDialog = true"
            >添加客户</el-button
          >
        </div>
        <div class="right">
          <el-select v-model="search.agent" placeholder="全部经纪">
            <el-option
              v-for="item in agentsList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
          <el-input
            v-model="search.name_contains"
            class="keyword"
            placeholder="请输入名称关键字"
          ></el-input>
          <el-button class="elbtn firstBtn" type="primary" @click="searchFn"
            >搜索</el-button
          >
          <el-button class="elbtn" type="warning" @click="reset"
            >重置搜索</el-button
          >
        </div>
      </div>
      <hr class="hr" />
      <el-table
        border
        height="600px"
        style="width: 100%"
        :data="clientsList[pageNum]"
      >
        <el-table-column label="图片">
          <template #default="{ row }">
            <img
              :src="row.image"
              v-fiximg="require('@/assets/12.16.jpg')"
              alt=""
            />
          </template>
        </el-table-column>
        <el-table-column label="名称" prop="name"> </el-table-column>
        <el-table-column label="邮箱" prop="email"> </el-table-column>
        <el-table-column label="电话" prop="phone"> </el-table-column>
        <el-table-column label="经纪" prop="agent.name"> </el-table-column>
        <el-table-column label="微信" prop="wechat"> </el-table-column>
        <el-table-column label="介绍" prop="desc"> </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="editClients(row.id)"
              >编辑</el-button
            >
            <el-button type="danger" size="small" @click="delClient(row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        layout="total,prev,pager,next"
        @current-change="currentChange"
        :page-size="pageSize"
        :total="clinets.length"
      ></el-pagination>
    </el-card>

    <!-- 编辑 -->
    <el-dialog
      :visible="showDialog"
      :title="addForm.id ? '编辑客户' : '添加客户'"
      @close="btnCancel"
    >
      <el-form
        label-width="96px"
        :rules="rules"
        :model="addForm"
        ref="ruleForm"
      >
        <el-form-item label="经纪" prop="agent">
          <el-select v-model="addForm.agent" placeholder="请选择经纪人">
            <el-option
              v-for="item in agentsList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input
            style="width: 96%"
            placeholder="请输入姓名"
            v-model="addForm.name"
          />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input
            style="width: 96%"
            placeholder="请输入正确的邮箱地址/如1234@qq.com"
            :rows="3"
            v-model="addForm.email"
          />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input
            style="width: 96%"
            placeholder="请输入正确的11位手机号码"
            v-model="addForm.phone"
          ></el-input>
        </el-form-item>
        <el-form-item label="微信">
          <el-input
            style="width: 96%"
            placeholder="请输入微信号"
            v-model="addForm.wechat"
          ></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="desc">
          <el-input
            style="width: 96%"
            placeholder="请输入相关描述信息"
            v-model="addForm.desc"
          ></el-input>
        </el-form-item>
        <el-form-item label="封面" prop="image">
          <UploadImage ref="UploadImage"></UploadImage>
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="space-start">
            <el-button @click="btnCancel" class="btnCancel">取消</el-button>
            <el-button type="primary" @click="btnOk" class="btnOk"
              >确定</el-button
            >
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { dimensionOneToTwo } from "@/share/index.js";
import UploadImage from "@/components/UploadImage";
import {
  getClientsList,
  delClients,
  getClientsCount,
  editClients,
  getClientsDetail,
  addClients,
} from "@/api/clients.js";
export default {
  components: { UploadImage },
  data() {
    const validateRegFn = (rule, value, callback) => {
      const reg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
      //console.log(value);
      reg.test(value)
        ? callback()
        : callback(new Error("您输入的邮箱格式不正确"));
    };

    const phoneValidator = (rule, val, callback) => {
      if (/^1[3456789]\d{9}$/.test(val)) {
        callback();
      } else {
        callback(new Error("手机号码格式有误"));
      }
    };
    return {
      fileList: [], //图片上传列表
      clientsList: [], //客户列表
      agentsList: [], //经纪列表
      search: {
        agent: "",
        name_contains: "",
      },
      page: {
        _limit: 4, //最大获取条数
        _start: 0, //开始获取条数位置
      },
      total: 0,
      pageNum: 0,
      pageSize: 4,
      showDialog: false,
      addForm: {
        agent: "",
        name: "",
        email: "",
        phone: "",
        wechat: "",
        desc: "",
        image: "",
      },
      clinets: [],
      rules: {
        name: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
        desc: [{ required: true, message: "描述不能为空", trigger: "blur" }],
        email: [
          { required: true, message: "邮箱不能为空", trigger: "blur" },
          { validator: validateRegFn, trigger: "blur" },
        ],
        image: [{ required: true, message: "图片不能为空", trigger: "change" }],
        agent: [{ required: true, message: "经纪人不能为空", trigger: "blur" }],
        phone: [
          { required: true, message: "手机号码不能为空", trigger: "blur" },
          { validator: phoneValidator, trigger: "blur" },
        ],
      },
    };
  },
  async created() {
    await this.getClientsList();
    //经济列表
    this.agentsList = this.$store.getters.agentList;
  },
  methods: {
    //重置搜索
    async reset() {
      this.search.agent = "";
      this.search.name_contains = "";
      await this.getClientsList();
    },
    //搜索
    async searchFn() {
      const obj = {};
      for (const key in this.search) {
        if (this.search[key]) {
          obj[key] = this.search[key];
        }
      }
      if (!JSON.stringify(obj) === "{}") {
        this.$message.warning("没有搜索的数据");
        return;
      }
      await this.getClientsCount();
      this.clinets = await getClientsList({
        ...this.page,
        ...obj,
      });
      if (!this.clinets.length) {
        this.$message.warning("没有您要搜索的数据！");
        this.reset();
        return;
      }
      this.clientsList = dimensionOneToTwo(this.clinets, this.pageSize);
    },
    // 分頁功能
    async currentChange(curPage) {
      this.pageNum = curPage - 1;
    },
    //获取客户列表
    async getClientsList() {
      await this.getClientsCount();
      this.clinets = await getClientsList(this.page);
      this.clientsList = dimensionOneToTwo(this.clinets, this.pageSize);
    },
    //获取客户数量
    async getClientsCount() {
      this.total = await getClientsCount();
      this.page._limit = this.total;
    },
    //删除
    async delClient(id) {
      try {
        await this.$confirm("确定删除吗");
        await delClients(id);
        this.$message.success("操作成功");
        this.getClientsList();

        if (this.clientsList[this.pageNum].length === 1) {
          this.pageNum--;
          this.getClientsList();
        }
      } catch (error) {
        console.log(error);
      }
    },
    //取消
    btnCancel() {
      this.$refs.UploadImage.fileList = [];
      this.showDialog = false;
      this.$refs.ruleForm.resetFields();
      this.addForm = {
        agent: "",
        name: "",
        email: "",
        phone: "",
        wechat: "",
        desc: "",
        image: "",
      };
    },
    //确定
    async btnOk() {
      try {
        this.addForm.image = this.$refs.UploadImage.fileList[0]?.url;
        this.$refs.ruleForm.validateField("image");
        await this.$refs.ruleForm.validate();
        if (this.addForm.id) {
          //编辑
          await editClients(this.addForm);
        } else {
          //新增
          await addClients(this.addForm);
        }
        this.$message.success("操作成功");
        this.showDialog = false;
        await this.getClientsList();
        this.$refs.ruleForm.resetFields();
        this.addForm = {
          agent: "",
          name: "",
          email: "",
          phone: "",
          wechat: "",
          desc: "",
          image: "",
        };
      } catch (error) {
        console.log(error);
        this.$message.error("你还没有输入呢");
      }
    },
    //编辑数据回显
    async editClients(id) {
      this.addForm = await getClientsDetail(id);
      this.addForm = { ...this.addForm, agent: this.addForm.agent?.id };
      setTimeout(() => {
        this.$refs.ruleForm.validateField("image");
        this.$refs.UploadImage.fileList = [];
        this.$refs.UploadImage.fileList.push({
          name: this.addForm.title,
          url: this.addForm.image,
        });
      }, 10);
      this.showDialog = true;
    },
  },
  watch: {
    name_contains(newVal) {
      if (!newVal) this.getClientsList();
    },
  },
};
</script>

<style lang="less" scoped>
.hr {
  border: none;
  height: 1px;
  background-color: rgba(204, 204, 204, 0.267);
}
/deep/.el-table {
  margin: 20px 0;
}
/deep/.btn {
  margin-bottom: 20px;
}
.title {
  display: flex;
  justify-content: space-between;
  .right {
    display: flex;
    .elbtn {
      height: 40px;
    }
  }
}
/deep/.el-select {
  .el-input__inner {
    width: 150px;
  }
}
.keyword {
  margin: 0 10px;
}
img {
  width: 120px;
  height: 120px;
  //border-radius: 50%;
}
/deep/.el-pagination {
  text-align: center;
}
.firstBtn {
  margin-right: 10px;
}
img {
  width: 160px !important;
  height: 136px;
}

.btnCancel {
  margin-left: 200px;
  margin-right: 50px;
}

.btnOk {
  margin-left: 50px;
}

/deep/.el-dialog__header {
  background-color: #6cf;
  .el-dialog__title {
    color: #fff;
  }
}
</style>